package com.samsung.controller.user;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.samsung.common.annotation.LoginAjaxAuth;
import com.samsung.common.annotation.LoginAuth;
import com.samsung.common.util.BaseUtil;
import com.samsung.common.util.CalculatePage;
import com.samsung.common.util.Constant;
import com.samsung.dto.common.BaseJsonResult;
import com.samsung.dto.common.JCommand;
import com.samsung.dto.common.JErrorResult;
import com.samsung.dto.common.JSuccResult;
import com.samsung.model.user.User;
import com.samsung.service.user.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	/**
	* @Title: loginPage
	* @Description: 
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping("/loginPage")
	public ModelAndView loginPage(HttpServletRequest request, String callback) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("login");
		if(BaseUtil.isEmpty(callback) || "null".equalsIgnoreCase(callback)) {
			callback = "";
		}
		mav.addObject("callback", callback);
		
		return mav;
	}
	
	/**
	 * 
	* @Title: login
	* @Description: 登录操作逻辑
	* @param @param request
	* @param @param response
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @throws
	 */
	@ResponseBody
	@RequestMapping("/login")
	public Object login(HttpServletRequest request,
			HttpServletResponse response, String callback) {
		String uid = request.getParameter("uid");
		String password = request.getParameter("password");
		if (null == uid || null == password) {
			return new JErrorResult("用户名和密码不能为空");
		}
		User user = userService.selectByPrimaryKey(uid);
		if(null == user){
			return new JErrorResult("用户不存在");
		}
		if (!user.getPassword().equals(BaseUtil.md5(password))) {
			return new JErrorResult("用户名和密码不正确");
		}
		request.getSession().setAttribute(Constant.LOGIN_TOKEN, user);
		if(BaseUtil.isEmpty(callback) || "null".equalsIgnoreCase(callback)) {
			callback = "";
		}
		return new JSuccResult("登录成功", null, callback);
	}

	/**
	 * 
	* @Title: logout
	* @Description: 退出系统
	* @param @param request
	* @param @param response
	* @param @param model
	* @param @throws IOException    设定文件
	* @return void    返回类型
	* @throws
	 */
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request, HttpServletResponse response, ModelAndView model)
			throws IOException {
		request.getSession().removeAttribute(Constant.LOGIN_TOKEN);

		response.sendRedirect(request.getContextPath() + "/index.html");
	}
	/**
	 * 
	* @Title: registPage
	* @Description: 注册页面跳转
	* @author cfe
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping("/registPage")
	public ModelAndView registPage(HttpServletRequest request, String callback) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("regist");
		if(BaseUtil.isEmpty(callback) || "null".equalsIgnoreCase(callback)) {
			callback = "";
		}
		mav.addObject("callback", callback);
		
		return mav;
	}

	/**
	 * 
	* @Title: regist
	* @Description: 注册用户逻辑
	* @param @param request
	* @param @param response
	* @param @return    设定文件
	* @return Object    返回类型
	* @throws
	 */
	@RequestMapping("/regist")
	@ResponseBody
	public Object regist(HttpServletRequest request,
			HttpServletResponse response) {
		User user = userService.selectByPrimaryKey(request.getParameter("uid"));
		Map<String, Object> model = new HashMap<String, Object>();
		//判断注册的用户名是否存在
		if(user != null) {
			model.put("flag", false);
			model.put("msg", "该用户已存在");
			return model;
		}
		
		User u = new User();
		u.setUid(request.getParameter("uid"));
		u.setName(request.getParameter("name"));
		u.setPassword(BaseUtil.md5(request.getParameter("password")));
		u.setMail(request.getParameter("email"));
		u.setUserImage("/resource/avatar/default.gif");
		u.setCreateTime(new Date());
		u.setMobile("");
		u.setType(1);
		u.setStatus(0);
		int cnt = userService.regist(u);
		if(cnt > 0) {
			model.put("flag", true);
			model.put("msg", "注册成功");
			return model;
		}
		
		return model;
	}
	
	/**
	 * 
	* @Title: validateOldPassword
	* @Description: 验证旧密码是否输入正确
	* @param @param request
	* @param @param response
	* @param @param user
	* @param @return    设定文件
	* @return boolean    返回类型
	* @throws
	 */
	@LoginAjaxAuth
	@RequestMapping("/validateOldPassword")
	@ResponseBody
	public BaseJsonResult validateOldPassword(HttpServletRequest request, HttpServletResponse response,User user){
		String oldPwd=request.getParameter("oldPwd");
		User u=(User) request.getSession().getAttribute(Constant.LOGIN_TOKEN);
		if (null!=u && null!=oldPwd) {
			String md5Password =  BaseUtil.md5(oldPwd);
			if(u.getPassword().equals(md5Password)){
				return new JSuccResult();
			}else{
				return new JErrorResult();
			}
		}
		return new JErrorResult("参数错误或未登录");
	}
	
	/**
	 * 
	* @Title: changePassword
	* @Description: 修改密码
	* @param @param request
	* @param @param response
	* @param @param user
	* @param @return    设定文件
	* @return int    返回类型
	* @throws
	 */
	@LoginAjaxAuth
	@RequestMapping("/changePassword")
	@ResponseBody
	public Object changePassword(HttpServletRequest request, HttpServletResponse response,User user){
		String newPwd=request.getParameter("newPwd");
		String oldPwd=request.getParameter("oldPwd");
		User u=(User) request.getSession().getAttribute(Constant.LOGIN_TOKEN);
		if (null!=u && BaseUtil.isNotEmpty(oldPwd) && BaseUtil.isNotEmpty(newPwd)) {
			if(u.getPassword().equals(BaseUtil.md5(oldPwd.trim()))){
				user.setUid(u.getUid());
				user.setPassword(BaseUtil.md5(newPwd.trim()));
				userService.update(user);
				request.getSession().removeAttribute(Constant.LOGIN_TOKEN);
			} else {
				return new JErrorResult("原始密码不正确");
			}
		}
		return new JSuccResult();
	}
	

	/**
	* @Title: manage
	* @Description: 用户管理界面
	* @param @return   设定文件
	* @return ModelAndView    返回类型
	* @throws 
	 */
	@LoginAuth
	@RequestMapping("/manage")
	public ModelAndView manage(@RequestParam("currentPage")int currentPage,HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("user/manage");
		User user=(User) request.getSession().getAttribute(Constant.LOGIN_TOKEN);
		if(user==null||user.getType()==1){
			mav.setViewName("/login");
		}
		/*分页*/
		List<User> userList = userService.getAllUser();
		Map<String, Integer> resultMap = CalculatePage.getPageData(userList, currentPage,10);
		mav.addObject("currentPage",resultMap.get("currentPage"));
		mav.addObject("userpageList",userService.getPageUser(resultMap.get("startIndex")));
		mav.addObject("totalPage",resultMap.get("totalPage"));
		return mav;
	}
	
	/**
	 * 
	* @Title: checkMail
	* @Description: 对用户名和邮箱进行验证
	* @param @param res
	* @param @param uid
	* @param @param email
	* @param @return    设定文件
	* @return User    返回类型
	* @throws
	 */
	@ResponseBody
	@RequestMapping("/checkMail")
	public Object checkMail(HttpServletRequest res,String uid,String email){
		if(BaseUtil.isEmpty(uid) && BaseUtil.isEmpty(email)){
			return new JErrorResult("验证失败");
		}
		String mail = email;
		User user = userService.selectByPrimaryKey(uid);
		if(user != null){
			if(mail.equals(user.getMail())){
				res.getSession().setAttribute("uid", user.getUid());
				res.getSession().setAttribute("CHANGE_PWD", BaseUtil.getUUID());
				return new JSuccResult(user);
			}
		}
		return new JErrorResult("验证失败");
	}
	
	/**
	 * 
	* @Title: changePassword
	* @Description: 执行修改密码操作
	* @param @param res
	* @param @param password
	* @param @return    设定文件
	* @return boolean    返回类型
	* @throws
	 */
	@ResponseBody
	@RequestMapping("/password/reset")
	public Object forgetPassword(HttpServletRequest res, String uid, String email, String password){
		if(BaseUtil.isEmpty(uid) || BaseUtil.isEmpty(email) || BaseUtil.isEmpty(password)){
			return new JErrorResult("参数不完整，请检查");
		}
		
		User user = userService.selectByPrimaryKey(uid);
		if(user==null) {
			return new JErrorResult("用户不存在，请检查");
		}
		if(BaseUtil.isNotEmpty(user.getMail()) && user.getMail().equalsIgnoreCase(email.trim())) {
			user.setPassword(BaseUtil.md5(password));
			if(userService.update(user) > 0){
				return new JSuccResult("修改完成");
			}
		}
		
		return new JErrorResult("验证失败");
	}
	
	/**
	* 
	* @Title: changePassword
	* @Description: 获取所有可用用户的信息以填充备选单
	* @return list   
	* @throws
	*/
	@ResponseBody
	@RequestMapping("/fillAllUsers")
	public List<User> fillAllUsers(){
		return userService.getAllUser();
	}
	
	@ResponseBody
	@RequestMapping("/getAllUserId")
	public List<User> getAllUserId(){
		return userService.getAllUserId();
	}
	
	/**
	 * 修改用户信息
	 */
	@ResponseBody
	@RequestMapping("/profile/update")
	@LoginAjaxAuth
	public Object profileUpdate(HttpServletRequest request) {
		// 获取用户Session
		User user = (User) request.getSession().getAttribute(Constant.LOGIN_TOKEN);
		String uid = user.getUid();
		
		User dbUser = userService.selectByPrimaryKey(uid);
		if (dbUser == null) {
			request.getSession().removeAttribute(Constant.LOGIN_TOKEN);
			return new JCommand("用户信息不存在或已被删除，请重新登陆", Constant.AjaxCommand.LOGIN);
		}
		
		String name = request.getParameter("name");
		String mail = request.getParameter("mail");
		String mobile = request.getParameter("mobile");
		
		if(BaseUtil.isNotEmpty(name)) {
			dbUser.setName(name);
		}
		if(BaseUtil.isNotEmpty(mail)) {
			dbUser.setMail(mail);
		}
		if(BaseUtil.isNotEmpty(mobile)) {
			dbUser.setMobile(mobile);
		}
		System.out.println(dbUser);
		int cnt = userService.update(dbUser);
		if(cnt > 0) {
			request.getSession().setAttribute(Constant.LOGIN_TOKEN, dbUser);
			return new JSuccResult("修改完成");
		}
		
		return new JCommand("修改失败", "LOGIN", request.getHeader("Referer"));
	}
	
	/**
	 * 修改用户密码
	 */
	@ResponseBody
	@RequestMapping("/password/update")
	@LoginAjaxAuth
	public Object passwordUpdate(HttpServletRequest request) {
		// 获取用户Session
		User user = (User) request.getSession().getAttribute(Constant.LOGIN_TOKEN);
		String uid = user.getUid();
		
		User dbUser = userService.selectByPrimaryKey(uid);
		if (dbUser == null) {
			request.getSession().removeAttribute(Constant.LOGIN_TOKEN);
			return new JCommand("用户信息不存在或已被删除，请重新登陆", Constant.AjaxCommand.LOGIN);
		}
		
		String oldpwd = request.getParameter("oldpwd");
		String pwd = request.getParameter("password");
		
		if(BaseUtil.isEmpty(oldpwd) || BaseUtil.isEmpty(pwd)) {
			return new JErrorResult("旧密码或新密码不能为空");
		}
		
		if(!dbUser.getPassword().equalsIgnoreCase(BaseUtil.md5(oldpwd))) {
			return new JErrorResult("原密码不正确");
		}
		
		dbUser.setPassword(BaseUtil.md5(pwd));
		int cnt = userService.update(dbUser);
		if(cnt > 0) {
			request.getSession().setAttribute(Constant.LOGIN_TOKEN, dbUser);
			return new JSuccResult("修改完成");
		}
		
		return new JCommand("修改失败", "LOGIN", request.getHeader("Referer"));
	}

	/**
	 * 跳转个人信息页面
	 */
	@LoginAuth
	@RequestMapping(value = "/profile/page")
	public String profilePage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		
		return "user/profile";
	}
	
	/**
	 * 跳转修改密码页面
	 */
	@LoginAuth
	@RequestMapping(value = "/password/page")
	public String passwordPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		
		return "user/password";
	}
	
	/**
	 * 逻辑删除用户信息，并展示结果
	 */
	@LoginAjaxAuth
	@ResponseBody
	@RequestMapping("/deleteUserById")
	public Object deleteUserById(String singleId) {
		String[] idStrings=singleId.split(",");
		for (String uid : idStrings) {
			userService.delete(uid);
		}
		return new JSuccResult();
	}
	
	@ResponseBody
	@RequestMapping("/getAllUserIdCombo")
	public List<Map<String, String>> getAllUserIdCombo(){
		List<Map<String, String>> rs = new ArrayList<Map<String, String>>();
		List<User> list = userService.getAllUserId();
		for (User user : list) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("label", user.getUid());
			map.put("value", user.getUid());
			
			rs.add(map);
		}
		return rs;
	}

}